<template>
    <div class="tablelists-container">
        <!-- 参数选择区域 -->
        <div class="parameter-section">
            <el-card class="parameter-card">
                <template #header>
                    <div class="card-header">
                        <span>时间范围选择</span>
                    </div>
                </template>
                <div class="button-group">
                    <el-button 
                        type="primary" 
                        :class="{ active: selectedDays === 0 }"
                        @click="selectTimeRange(0)"
                    >
                        今日
                    </el-button>
                    <el-button 
                        type="primary" 
                        :class="{ active: selectedDays === 1 }"
                        @click="selectTimeRange(1)"
                    >
                        昨天
                    </el-button>
                    <el-button 
                        type="primary" 
                        :class="{ active: selectedDays === 7 }"
                        @click="selectTimeRange(7)"
                    >
                        近一周
                    </el-button>
                    <el-button 
                        type="primary" 
                        :class="{ active: selectedDays === 30 }"
                        @click="selectTimeRange(30)"
                    >
                        近一个月
                    </el-button>
                </div>
            </el-card>
        </div>

        <!-- 图表容器 -->
        <div ref="chartContainer" class="chart-container"></div>

        <!-- 数据列表 -->
        <div class="data-list-section">
            <el-card class="data-list-card">
                <template #header>
                    <div class="card-header">
                        <span>仓库详细信息列表</span>
                        <div class="header-actions">
                            <el-button type="primary" size="small" @click="exportData">
                                <el-icon><Download /></el-icon>
                                导出数据
                            </el-button>
                        </div>
                    </div>
                </template>
                
                <el-table 
                    :data="warehouseListData" 
                    style="width: 100%"
                    :loading="tableLoading"
                    stripe
                    border
                >
                    <el-table-column type="index" label="序号" width="60" align="center" />
                    
                    <el-table-column prop="warename" label="仓库名称" width="150" align="center">
                        <template #default="{ row }">
                            <el-tag type="primary" size="small">{{ row.warename }}</el-tag>
                        </template>
                    </el-table-column>
                    
                 
                    
                    <el-table-column prop="inventory" label="库存数量" width="120" align="center">
                        <template #default="{ row }">
                            <span class="number-highlight">{{ row.inventory }}</span>
                        </template>
                    </el-table-column>
                    
                    <el-table-column prop="sumMoney" label="库存金额" width="150" align="center">
                        <template #default="{ row }">
                            <span class="money-highlight">¥{{ formatMoney(row.sumMoney) }}</span>
                        </template>
                    </el-table-column>
                    
                    <el-table-column prop="turnoverRate" label="周转率" width="120" align="center">
                        <template #default="{ row }">
                            <el-progress 
                                :percentage="row.turnoverRate" 
                                :color="getProgressColor(row.turnoverRate)"
                                :show-text="false"
                            />
                            <span class="rate-text">{{ row.turnoverRate }}%</span>
                        </template>
                    </el-table-column>
                    
                    <el-table-column prop="times" label="操作时间" width="180" align="center">
                        <template #default="{ row }">
                            <el-tag type="info" size="small">{{ formatDate(row.times) }}</el-tag>
                        </template>
                    </el-table-column>
                    
                    <el-table-column label="操作" width="150" align="center">
                        <template #default="{ row }">
                            <el-button link type="primary" size="small" @click="viewDetails(row)">
                                查看详情
                            </el-button>
                            <el-button link type="success" size="small" @click="exportRow(row)">
                                导出
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 统计信息 -->
                <div class="statistics-section">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <div class="stat-item">
                                <div class="stat-label">仓库总数</div>
                                <div class="stat-value">{{ warehouseListData.length }}</div>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div class="stat-item">
                                <div class="stat-label">总库存数量</div>
                                <div class="stat-value">{{ totalInventory }}</div>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div class="stat-item">
                                <div class="stat-label">总库存金额</div>
                                <div class="stat-value">¥{{ formatMoney(totalMoney) }}</div>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div class="stat-item">
                                <div class="stat-label">平均周转率</div>
                                <div class="stat-value">{{ averageTurnoverRate }}%</div>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { Download } from '@element-plus/icons-vue';
import service from '@/utils/request';

// 类型定义
interface WarehouseData {
    warename: string;
    inventory: number;
    sumMoney: number;
    times: string;
}

interface WarehouseListData extends WarehouseData {
    turnoverRate: number;
}

interface ApiResponse {
    code: number;
    message: string;
    resultData: WarehouseData[];
}

const chartContainer = ref<HTMLElement | null>(null);
const selectedDays = ref<number>(0);
const warehouseListData = ref<WarehouseListData[]>([]);
const tableLoading = ref<boolean>(false);
let myChart: echarts.ECharts | null = null;

// 计算属性
const totalInventory = computed(() => {
    return warehouseListData.value.reduce((sum, item) => sum + item.inventory, 0);
});

const totalMoney = computed(() => {
    return warehouseListData.value.reduce((sum, item) => sum + item.sumMoney, 0);
});

const averageTurnoverRate = computed(() => {
    if (warehouseListData.value.length === 0) return 0;
    const totalRate = warehouseListData.value.reduce((sum, item) => sum + item.turnoverRate, 0);
    return Math.round(totalRate / warehouseListData.value.length * 10) / 10;
});

// 获取仓库数据
const fetchWarehouseData = async (days: number): Promise<WarehouseData[]> => {
    try {
        console.log('正在获取数据，参数:', days);
        const response = await service.get<ApiResponse>('/api/app/standing__Book/wae-house', {
            params: { days }
        });
        
        console.log('API响应:', response.data);
        
        if (response.data.code === 200) {
            console.log('获取到的数据:', response.data.resultData);
            return response.data.resultData;
        } else {
            ElMessage.error(response.data.message || '获取数据失败');
            return [];
        }
    } catch (error) {
        console.error('获取仓库数据失败:', error);
        ElMessage.error('获取数据失败，请稍后重试');
        return [];
    }
};

// 计算周转率
const calculateTurnoverRate = (inventory: number, sumMoney: number): number => {
    const densityRate = sumMoney > 0 ? (inventory / sumMoney) * 1000 : 0;
    return Math.min(100, Math.max(0, Math.round(densityRate * 10) / 10));
};

// 格式化金额
const formatMoney = (amount: number): string => {
    return amount.toLocaleString('zh-CN');
};

// 格式化日期时间
const formatDateTime = (dateTime: string): string => {
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
};

// 格式化日期（用于图表横坐标）
const formatDate = (dateTime: string): string => {
    const date = new Date(dateTime);
    const now = new Date();
    const diffTime = Math.abs(now.getTime() - date.getTime());
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    // 根据选择的时间范围调整显示格式
    if (selectedDays.value === 0) {
        // 今日：显示年月日 + 具体时间
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    } else if (selectedDays.value === 1) {
        // 昨天：显示年月日 + 具体时间
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    } else if (selectedDays.value === 7) {
        // 近一周：显示年月日
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        });
    } else {
        // 近一个月：显示年月日
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        });
    }
};

// 格式化日期（用于图表横坐标，显示仓库名称和时间）
const formatDateForChart = (dateTime: string): string => {
    const date = new Date(dateTime);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
};

// 获取进度条颜色
const getProgressColor = (rate: number): string => {
    if (rate >= 80) return '#67C23A';
    if (rate >= 60) return '#E6A23C';
    if (rate >= 40) return '#F56C6C';
    return '#909399';
};

// 格式化操作时间
const formatOperationTime = (dateTime: string): string => {
    const date = new Date(dateTime);
    return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
};

// 更新图表数据
const updateChart = async (days: number) => {
    if (!myChart) return;
    
    try {
        tableLoading.value = true;
        const data = await fetchWarehouseData(days);
        
        if (data.length === 0) {
            ElMessage.warning('暂无数据');
            return;
        }

        // 处理列表数据
        warehouseListData.value = data.map(item => ({
            ...item,
            turnoverRate: calculateTurnoverRate(item.inventory, item.sumMoney)
        }));

        // 按仓库和时间分组数据
        const warehouseTimeGroups = new Map<string, {
            inventory: number;
            sumMoney: number;
            count: number;
            times: string;
        }>();

        data.forEach(item => {
            const date = formatDateForChart(item.times);
            const warehouseTimeKey = `${item.warename}-${date}`;
            
            if (warehouseTimeGroups.has(warehouseTimeKey)) {
                const group = warehouseTimeGroups.get(warehouseTimeKey)!;
                group.inventory += item.inventory;
                group.sumMoney += item.sumMoney;
                group.count += 1;
            } else {
                warehouseTimeGroups.set(warehouseTimeKey, {
                    inventory: item.inventory,
                    sumMoney: item.sumMoney,
                    count: 1,
                    times: item.times
                });
            }
        });

        // 提取图表数据
        const warehouseTimeLabels = Array.from(warehouseTimeGroups.keys()).sort();
        const inventoryData = warehouseTimeLabels.map(key => warehouseTimeGroups.get(key)!.inventory);
        const moneyData = warehouseTimeLabels.map(key => warehouseTimeGroups.get(key)!.sumMoney);
        const turnoverRates = warehouseTimeLabels.map(key => {
            const group = warehouseTimeGroups.get(key)!;
            return calculateTurnoverRate(group.inventory, group.sumMoney);
        });

        // 调试信息
        console.log('图表数据:', {
            labels: warehouseTimeLabels,
            inventory: inventoryData,
            money: moneyData,
            turnover: turnoverRates
        });

        // 检查是否有数据
        if (warehouseTimeLabels.length === 0) {
            ElMessage.warning('暂无数据可显示');
            return;
        }

        // 图表配置
        const option = {
            title: {
                text: `库存趋势分析 (${getTimeRangeText(days)})`,
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function(params: any) {
                    const label = params[0].name;
                    const parts = label.split('-');
                    let result = '';
                    
                    if (parts.length >= 2) {
                        const warehouseName = parts[0];
                        const date = parts.slice(1).join('-');
                        result = `仓库: ${warehouseName}<br/>日期: ${date}<br/>`;
                    } else {
                        result = `${label}<br/>`;
                    }
                    
                    params.forEach((param: any) => {
                        if (param.seriesName === '库存量') {
                            result += `${param.seriesName}: ${param.value}<br/>`;
                        } else if (param.seriesName === '周转率') {
                            result += `${param.seriesName}: ${param.value}%<br/>`;
                        } else if (param.seriesName === '库存金额') {
                            result += `${param.seriesName}: ¥${formatMoney(param.value)}<br/>`;
                        }
                    });
                    return result;
                }
            },
            legend: {
                data: ['库存量', '周转率', '库存金额'],
                top: 30
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '30%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: warehouseTimeLabels,
                name: '仓库名称-时间',
                nameLocation: 'center',
                nameGap: 50,
                nameTextStyle: {
                    fontSize: 14,
                    fontWeight: 'bold',
                    color: '#2c3e50',
                    padding: 80,
                },
                axisLabel: {
                    rotate: 0,
                    fontSize: 12,
                    color: '#333',
                    lineHeight: 16,
                    margin: 25,
                    fontWeight: 'bold',
                    formatter: function(value: string) {
                        // 格式化显示：仓库名称 + 日期
                        const parts = value.split('-');
                        if (parts.length >= 2) {
                            const warehouseName = parts[0];
                            const date = parts.slice(1).join('-');
                            // 显示完整年月日
                            return `${warehouseName}\n${date}`;
                        }
                        return value;
                    }
                },
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: '库存量',
                    min: 0,
                    position: 'left',
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                {
                    type: 'value',
                    name: '周转率(%)',
                    min: 0,
                    max: 100,
                    position: 'right',
                    axisLabel: {
                        formatter: '{value}%'
                    }
                },
                {
                    type: 'value',
                    name: '库存金额',
                    min: 0,
                    position: 'right',
                    offset: 80,
                    axisLabel: {
                        formatter: '¥{value}'
                    }
                }
            ],
            series: [
                {
                    name: '库存量',
                    type: 'bar',
                    data: inventoryData,
                    itemStyle: {
                        color: '#5470C6'
                    },
                    barWidth: '30%'
                },
                {
                    name: '周转率',
                    type: 'line',
                    yAxisIndex: 1,
                    data: turnoverRates,
                    itemStyle: {
                        color: '#EE6666'
                    },
                    symbol: 'circle',
                    symbolSize: 8,
                    lineStyle: {
                        width: 3
                    }
                },
                {
                    name: '库存金额',
                    type: 'bar',
                    yAxisIndex: 2,
                    data: moneyData,
                    itemStyle: {
                        color: '#91CC75'
                    },
                    barWidth: '30%'
                }
            ]
        };

        console.log('设置图表配置:', option);
        myChart.setOption(option);
        console.log('图表设置完成');
    } catch (error) {
        console.error('更新图表失败:', error);
    } finally {
        tableLoading.value = false;
    }
};

// 获取时间范围文本
const getTimeRangeText = (days: number): string => {
    switch (days) {
        case 0:
            return '今日';
        case 1:
            return '昨天';
        case 7:
            return '近一周';
        case 30:
            return '近一个月';
        default:
            return `${days}天`;
    }
};

// 选择时间范围
const selectTimeRange = (days: number) => {
    selectedDays.value = days;
    updateChart(days);
};

// 查看详情
const viewDetails = (row: WarehouseListData) => {
    ElMessage.info(`查看 ${row.warename} 的详细信息`);
    // 这里可以跳转到详情页面或打开详情弹窗
};

// 导出单行数据
const exportRow = (row: WarehouseListData) => {
    const data = {
        仓库名称: row.warename,
        操作时间: formatOperationTime(row.times),
        库存数量: row.inventory,
        库存金额: `¥${formatMoney(row.sumMoney)}`,
        周转率: `${row.turnoverRate}%`,
        更新时间: formatDate(row.times)
    };
    
    // 创建CSV内容
    const csvContent = Object.entries(data)
        .map(([key, value]) => `${key},${value}`)
        .join('\n');
    
    // 下载文件
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `${row.warename}_数据_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
    
    ElMessage.success(`已导出 ${row.warename} 的数据`);
};

// 导出所有数据
const exportData = () => {
    if (warehouseListData.value.length === 0) {
        ElMessage.warning('暂无数据可导出');
        return;
    }
    
    const headers = ['仓库名称', '操作时间', '库存数量', '库存金额', '周转率', '更新时间'];
    const csvContent = [
        headers.join(','),
        ...warehouseListData.value.map(row => [
            row.warename,
            formatOperationTime(row.times),
            row.inventory,
            `¥${formatMoney(row.sumMoney)}`,
            `${row.turnoverRate}%`,
            formatDate(row.times)
        ].join(','))
    ].join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `仓库数据_${getTimeRangeText(selectedDays.value)}_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
    
    ElMessage.success('数据导出成功');
};

// 监听时间范围变化
watch(selectedDays, (newDays) => {
    updateChart(newDays);
});

onMounted(() => {
    console.log('组件挂载，图表容器:', chartContainer.value);
    if (!chartContainer.value) {
        console.error('图表容器未找到');
        return;
    }
    
    // 初始化图表
    myChart = echarts.init(chartContainer.value);
    console.log('图表初始化完成');
    
    // 响应式调整
    const resizeHandler = () => {
        if (myChart) {
            myChart.resize();
        }
    };
    window.addEventListener('resize', resizeHandler);
    
    // 初始加载数据
    updateChart(selectedDays.value);
    
    // 组件卸载时移除监听器
    onUnmounted(() => {
        window.removeEventListener('resize', resizeHandler);
        if (myChart) {
            myChart.dispose();
        }
    });
});
</script>

<style lang="scss" scoped>
.tablelists-container {
    padding: 20px;
    background: linear-gradient(135deg, #e3f0ff 0%, #f8fbff 100%);
    min-height: 100vh;
}

.parameter-section {
    margin-bottom: 20px;
}

.parameter-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
    font-size: 16px;
    font-weight: bold;
    color: #2c3e50;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.button-group {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
}

.button-group .el-button {
    min-width: 100px;
    transition: all 0.3s ease;
}

.button-group .el-button.active {
    background: #409eff;
    border-color: #409eff;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.button-group .el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.chart-container {
    width: 100%;
    height: 700px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin-bottom: 20px;
}

.data-list-section {
    margin-top: 20px;
}

.data-list-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.number-highlight {
    font-weight: bold;
    color: #409eff;
    font-size: 14px;
}

.money-highlight {
    font-weight: bold;
    color: #67c23a;
    font-size: 14px;
}

.rate-text {
    margin-left: 8px;
    font-size: 12px;
    color: #606266;
}

.statistics-section {
    margin-top: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
}

.stat-item {
    text-align: center;
    padding: 15px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 8px;
}

.stat-value {
    font-size: 20px;
    font-weight: bold;
    color: #2c3e50;
}

// 表格样式优化
:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.el-table th) {
    background-color: #f5f7fa;
    color: #2c3e50;
    font-weight: bold;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: #fafbfc;
}

:deep(.el-progress) {
    margin-right: 8px;
}
</style>
